package com.blackfish.device;

import java.util.List;

import com.blackfish.common.model.DeviceBelong;
import com.blackfish.common.model.DeviceKeys;
import com.blackfish.common.untils.ShaUntil;
import com.blackfish.common.model.Device;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class DeviceService {
    public static final Device dao = new Device().dao();
    public static final DeviceKeys keysDao = new DeviceKeys().dao();
    public static final DeviceBelong belongDao = new DeviceBelong().dao();

    public String getNameById(int id) {
        return this.findById(id).getName();
    }

    public int getIdByName(String name) {
        return dao.findFirst("select * from active where name='" + name + "'").getId();
    }

    public Device findById(int id) {
        return dao.findById(id);
    }

    public List<Device> findAll() {
        return dao.find("select * from device order by id asc");
    }

    public List<Record> getAllJson() {
        return Db.find("select d.id,d.name as device_name,d.init_key,u.name from device as d INNER JOIN user as u INNER JOIN device_belong as b on u.id=b.user_id and b.device_id=d.id");
    }

    public boolean saveDevice(String name) {
        String time = java.time.LocalTime.now().toString();
        String key = new ShaUntil().getSHA256StrJava(time);
        return new Device().set("name", name).set("init_key", key).save();
    }


    public int libHaveKeys(String key) {
        List<DeviceKeys> deviceKey = keysDao.find("select * from device_keys where initkey=\"" + key + "\"");
        if (deviceKey.size() == 0 || deviceKey.get(0).getTime() == 0) {
            return -1;
        } else {
            int time = deviceKey.get(0).getTime();
            // 使用次数为-1的时候可以无限次使用
            if (time != -1) {
                try {
                    deviceKey.get(0).setTime(time - 1).update();
                } catch (Exception e) {
                    return -1;
                }
            }
            return deviceKey.get(0).getId();
        }
    }

    public boolean userHaveDevice(int userId, String deviceName) {
        List<Record> devices = Db.find("select * from device as d inner join device_belong as b on b.device_id=d.id and b.user_id=" + userId + " and d.name=\"" + deviceName + "\"");
        if (devices.size() == 0) {
            return false;
        }
        return true;
    }


    /*
     * 创建设备
     * 1，检查是否这个设备号存在，再检查是否使用次数过大
     * 2，检查用户是否有相同的设备已经添加，主要检查设备名称是否重复，因为需要通过设备名称获得key，通过key向im系统发送消息
     * 如果两个名字不同，但是key相同，实际上是可以通知到设备的，但是如果名称相同，key不同，那么可能会出现问题，用户不能获得
     * module的key，但是可以知道module的名字
     * */
    public Device creatDevice(String name, String key, int userId) {
        String time = java.time.LocalTime.now().toString();
        int keyId = libHaveKeys(key);
        boolean haveDevice = true;//!userHaveDevice(userId, name);
        if (keyId != -1 && haveDevice) {
            return new Device().set("name", name).set("init_key", key);
        }
        return null;
    }


    /*
     * 创建deviec和user的所属关系
     * */
    public boolean creatBelong(int userId, int deviceId) {
        return new DeviceBelong().set("device_id",deviceId).set("user_id",userId).save();
    }

    public List<Device> getDeviceByUser(int userId) {
        return dao.find("select d.name from device as d inner join device_belong as b on d.id=b.device_id and b.user_id=" + userId);
    }


    /*
     * 保存devices和其与用户的所属关系
     *
     * */
    public boolean saveDevice(List<Device> devices, int userId) {

        try {
            for (Device device : devices) {
                device.save();
            }
        } catch (Exception e) {
            for (Device device : devices) {
                device.delete();
            }
            return false;
        }

        try {
            for (Device device : devices) {
                creatBelong(userId,device.getId());
            }
        } catch (Exception e) {
            System.out.print(e.toString());
            for (Device device : devices) {
                device.delete();
            }
            return false;
        }
        return true;
    }

    public boolean deleteDevice(int id) {
        return dao.deleteById(id);
    }

}
